package DemoTest.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.zip.ZipOutputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


public class FtpUtil {

	public FTPClient getFtpConnection()  {
		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.connect("39.96.33.164",21);
			// socket连接，设置socket连接超时时间
			ftpClient.setSoTimeout(10 * 60 * 1000);
			ftpClient.enterLocalPassiveMode();
			ftpClient.login("ejiao", "123456");
			 if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
	                System.out.println("未连接到FTP，用户名或密码错误。");
	                ftpClient.disconnect();
	            } else {
	                System.out.println("FTP连接成功。");
	            }
		} catch (SocketException  e) {
			e.printStackTrace();
			System.out.println("IP地址可能错误");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("端口可能错误");
		} 
		return ftpClient;
	}
	
	/**
	 * 从FTP服务器下载文件
	 * @param ftpPath
	 * @param localPath
	 * @param fileName
	 */
	public void downloadFTPClient(String ftpPath,String localPath,String fileName) {
		
		OutputStream os = null;
		try { 
			FTPClient ftpClient = getFtpConnection();
			ftpClient.setControlEncoding("UTF-8");
			ftpClient.enterRemotePassiveMode();
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.changeWorkingDirectory(ftpPath);
			File file = new File(localPath + fileName);
			os = new FileOutputStream(file);
			ftpClient.retrieveFile(fileName, os);
			os.flush(); 
            ftpClient.logout();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("没有找到" + ftpPath + "文件");
		}finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	//======================================
	
	public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
	String fileName, String localPath) {
		boolean result = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(host, port);
			// 如果采用默认端口，可以使用ftp.connect(host)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					File localFile = new File(localPath + "/" + ff.getName());
					
//					ZipOutputStream zip = new ZipOutputStream(out);
					
					
					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
				}
			}
			
			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}
	
	
	
	//获取某个路径下所有文件列表
	
	public static boolean downloadFileList(String host, int port, String username, String password, String remotePath,
	String fileName, String localPath) {
		boolean result = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(host, port);
			// 如果采用默认端口，可以使用ftp.connect(host)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();
			File images = new File("D://");
			if(!images.exists()) {
				images.mkdirs();
			}
			for (FTPFile ff : fs) {
				String name = ff.getName();
				File file = new File(localPath + "/" + ff.getName());
				
				
//				if (ff.getName().equals(name)) {
//					File localFile = new File(images + "/" + ff.getName());
					
					
					
					OutputStream is = new FileOutputStream(file);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
//				}
			}
			
			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	//创建文件夹
	public static void createDir(FTPClient ftp,String dirname){
		  try{
		    ftp.makeDirectory(dirname);
		    System.out.println("在目标服务器上成功建立了文件夹: " + dirname);
		  }catch(Exception ex){
		    System.out.println(ex.getMessage());
		  }
		}
	
	public static void main(String[] args) {
//		FtpUtil util = new FtpUtil();
//		util.downloadFTPClient("/opt/server/images/1.txt", "D:\\", "9.txt");
		FtpUtil.downloadFileList("39.96.33.164", 21, "ejiao", "123456", "/opt/server/images/", "1.txt", "D://");
		
		
		
	}
	
	
}
